<?php

/*
 * 获取我最新的聊天室
 */

class My_chatlogApp extends MemberbaseApp
{

    var $_user_id;
    var $_chatlog_mod;
    var $_member_mod;

    function __construct()
    {
        $this->My_chatlogApp();
    }

    function My_chatlogApp()
    {
        parent::__construct();
        $this->_user_id = intval($this->visitor->get('user_id'));
        $this->_chatlog_mod = &m('chatlog');
        $this->_member_mod = &m('member');
    }

    //图标类型  手机轮播图  手机分类  手机广告图
    function index()
    {
        $this->_curlocal(LANG::get('member_center'), 'index.php?app=member', LANG::get('my_chat_list'));
        $this->_curitem('my_chatlog');
        $this->_curmenu('my_chat_list');

//        $sql = 'SELECT * FROM '
//                . '(SELECT receiverid as contact_id,receiverid,senderid,sendtime,sendcontent FROM ' . DB_PREFIX . 'chatlog  WHERE (senderid = ' . $this->_user_id . ') AND (receiverid != ' . $this->_user_id . ') '
//                . 'UNION SELECT senderid as contact_id,receiverid,senderid,sendtime,sendcontent FROM ' . DB_PREFIX . 'chatlog WHERE (senderid != ' . $this->_user_id . ')  AND  (receiverid = ' . $this->_user_id . ')) '
//                . 'as b GROUP BY contact_id ORDER BY sendtime DESC;';
        $sqlOld = "SELECT *,if(a.sendtime > b.sendtime,a.sendtime, b.sendtime) AS csendtime,if(a.sendtime > b.sendtime, a.sendcontent, b.sendcontent)
 AS csendcontent,a.receiverid AS contact_id FROM ( SELECT *, concat(senderid, '-', receiverid) AS c FROM ecm_chatlog x 
 WHERE senderid = " . $this->_user_id . " AND receiverid != " . $this->_user_id . " AND sendtime in ( select max(sendtime) from `ecm_chatlog` 
 WHERE receiverid = x.receiverid) GROUP BY receiverid ORDER BY sendtime DESC ) a JOIN ( SELECT *, concat(receiverid, '-', senderid) 
 AS d FROM ecm_chatlog y WHERE senderid != " . $this->_user_id . " AND receiverid = " . $this->_user_id . " AND 
 sendtime in ( select max(sendtime) from `ecm_chatlog` WHERE senderid = y.senderid) GROUP BY senderid ORDER BY sendtime DESC ) as b ON a.c = b.d GROUP BY a.c
  ORDER BY csendtime DESC";
//        $sql = "SELECT *,if(a.sendtime > b.sendtime,a.sendtime, b.sendtime) AS csendtime,if(a.sendtime > b.sendtime, a.sendcontent, b.sendcontent) AS csendcontent FROM ( SELECT *, concat(senderid, '-', receiverid) AS c FROM ecm_chatlog WHERE senderid = 2 AND receiverid != 2 GROUP BY receiverid ORDER BY sendtime DESC ) a JOIN ( SELECT *, concat(receiverid, '-', senderid) AS d FROM ecm_chatlog WHERE senderid != 2 AND receiverid = 2 GROUP BY senderid ORDER BY sendtime DESC ) as b ON a.c = b.d GROUP BY a.c ORDER BY csendtime DESC";
        $resOld = $this->_chatlog_mod->db->query($sqlOld);
        while ($chat = $this->_chatlog_mod->db->fetchRow($resOld)) {
            $chat_listOld[] = $chat;
        }

        $page = $this->_get_page();
        $page_nolimit = array();

        $count = count($chat_listOld);
        if ($page) {
            $limit = $page['limit'];
        } else {
            $limit = '';
        }

        $sqlnew = "SELECT *,if(a.sendtime > b.sendtime,a.sendtime, b.sendtime) AS csendtime,if(a.sendtime > b.sendtime, a.sendcontent, b.sendcontent) AS csendcontent,a.receiverid AS contact_id FROM ( SELECT *, concat(senderid, '-', receiverid) AS c FROM ecm_chatlog x WHERE senderid = " . $this->_user_id . " AND receiverid != " . $this->_user_id . " AND sendtime in ( select max(sendtime) from `ecm_chatlog` WHERE receiverid = x.receiverid) GROUP BY receiverid ORDER BY sendtime DESC ) a JOIN ( SELECT *, concat(receiverid, '-', senderid) AS d FROM ecm_chatlog y WHERE senderid != " . $this->_user_id . " AND receiverid = " . $this->_user_id . " AND sendtime in ( select max(sendtime) from `ecm_chatlog` WHERE senderid = y.senderid) GROUP BY senderid ORDER BY sendtime DESC ) as b ON a.c = b.d GROUP BY a.c ORDER BY csendtime DESC limit " . $limit;

        $res = $this->_chatlog_mod->db->query($sqlnew);
        while ($chat = $this->_chatlog_mod->db->fetchRow($res)) {
            $chat_list[] = $chat;
        }
        foreach ($chat_list as $key => $chat) {
            $contact = $this->_member_mod->get(array(
                'fields' => 'user_name,portrait',
                'conditions' => 'user_id=' . $chat['contact_id'],
            ));
            $chat_list[$key]['contact_name'] = $contact['user_name'];
            empty($contact['portrait']) && $chat_list[$key]['contact_portrait'] = Conf::get('default_user_portrait');
        }


        $page['item_count'] = $count;

        $this->_format_page($page);
        $this->assign('page_info', $page);

        $this->assign('my_id', $this->_user_id);
        $this->assign('chat_list', $chat_list);
        $this->display('my_chatlog.index.html');
    }

    function chatlog()
    {
        if (!IS_POST) {
            $this->_curlocal(LANG::get('member_center'), 'index.php?app=member', LANG::get('my_ad_add'));
            $this->_curitem('my_chatlog');
            $this->_curmenu('my_chatlog_list');

            //消息接收ID
            $receiverid = empty($_GET['receiverid']) ? 0 : intval($_GET['receiverid']);
            //查看接收方信息
            $receiver_info = $this->_member_mod->get(array(
                'fields' => 'user_id,user_name,portrait',
                'conditions' => 'user_id=' . $receiverid,
            ));
            if (empty($receiver_info)) {
                $this->show_warning('User_not_exist');
                return;
            }
            $conditions = '(receiverid=' . $receiverid . ' AND senderid = ' . $this->_user_id . ') OR (receiverid=' . $this->_user_id . ' AND senderid=' . $receiverid . ')';
            $chatlog_list = $this->_chatlog_mod->find(array(
                'conditions' => $conditions,
            ));

            $my_info = $this->_member_mod->get(array(
                'fields' => 'user_id,user_name,portrait',
                'conditions' => 'user_id=' . $this->_user_id,
            ));
            foreach ($chatlog_list as $key => $chatlog) {
                if ($chatlog['receiverid'] == $receiverid) {
                    $chatlog_list[$key]['receivername'] = $receiver_info['user_name'];
                    $chatlog_list[$key]['receiverportrait'] = $receiver_info['portrait'];
                    $chatlog_list[$key]['sendername'] = $my_info['user_name'];
                    $chatlog_list[$key]['senderportrait'] = $my_info['portrait'];
                } else {
                    $chatlog_list[$key]['receivername'] = $my_info['user_name'];
                    $chatlog_list[$key]['receiverportrait'] = $my_info['portrait'];
                    $chatlog_list[$key]['sendername'] = $receiver_info['user_name'];
                    $chatlog_list[$key]['senderportrait'] = $receiver_info['portrait'];
                }
            }

            //把接收方为自己的消息全部设置为0,表示已读 
            $this->_chatlog_mod->edit('is_new = 1 AND receiverid=' . $this->_user_id, array('is_new' => 0));
            $this->assign('chatlog_list', $chatlog_list);
        }
    }

    function drop()
    {
        $ad_ids = isset($_GET['receiverid']) ? trim($_GET['receiverid']) : '';
        if (!$ad_ids) {
            $this->show_warning('no_such_ad');
            return;
        }

        $info = $this->_chatlog_mod->db->query("DELETE FROM ecm_chatlog WHERE senderid = " . $ad_ids . " OR receiverid = " . $ad_ids);
        if ($info != false) {    //删除
            $this->show_warning('删除失败');
            return;
        }
        $this->show_message('drop_ad_successed');
    }

    function reply()
    {
        if (!$_GET['otherid']) {
            $this->show_warning($this->_ad_mod->get_error());
        }
        $this->_curlocal(LANG::get('member_center'), 'index.php?app=member', LANG::get('my_chat_list'));
        $this->_curitem('my_chatlog');
        $_member_submenu = $this->_get_member_submenu();

        //查看并更新当前对话的对话时间
        $chatOther = &m('chatother');
        $phone_code = $chatOther->get(array(
            'conditions' => 'otherid = ' . $_GET['otherid']
        ));
        $time = time();
        if (empty($phone_code)) {
            $data['otherid'] = $_GET['otherid'];
            $data['createtime'] = $time;
            $res = $chatOther->add($data);
        } else {
            if ($time > $phone_code['createtime'] + 60 * 5) {
                $info = $chatOther->edit('otherid = ' . $_GET['otherid'], array('createtime' => time()));
            }
        }

        $where['start_time'] = $time - 60 * 5;
        $where['end_time'] = $time;

        $listOther = $chatOther->find(array(
            'conditions' => 'createtime > ' . $where['start_time'] . ' AND createtime <= ' . $where['end_time'],
            'order' => 'createtime desc'
        ));
        $newArr = array_values($listOther);

        foreach ($newArr as $key => &$value) {
            $value['user_name'] = $this->_member_mod->get(array(
                'fields' => 'user_name,portrait',
                'conditions' => 'user_id=' . $value['otherid'],
            ));
            $value['is_read'] = $this->_chatlog_mod->get(array(
                'conditions' => 'senderid = ' . $value['otherid'],
                'field' => 'is_read'
            ));
        }

        $this->assign('newArr', $newArr);


        $sql = 'SELECT * FROM '
            . '(SELECT receiverid as contact_id,receiverid,senderid,sendtime,sendcontent FROM ' . DB_PREFIX . 'chatlog  WHERE (senderid = ' . $_GET['otherid'] . ') AND (receiverid = ' . $this->_user_id . ') '
            . 'UNION SELECT senderid as contact_id,receiverid,senderid,sendtime,sendcontent FROM ' . DB_PREFIX . 'chatlog WHERE (senderid = ' . $this->_user_id . ')  AND  (receiverid = ' . $_GET['otherid'] . ')) '
            . 'as b ORDER BY sendtime;';
        $res = $this->_chatlog_mod->db->query($sql);
        while ($chat = $this->_chatlog_mod->db->fetchRow($res)) {
            $chat_list[] = $chat;
        }
        foreach ($chat_list as $key => $chat) {
            $contact = $this->_member_mod->get(array(
                'fields' => 'user_name,portrait,phone_mob',
                'conditions' => 'user_id=' . $chat['senderid'],
            ));
            $chat_list[$key]['receive_phone'] = $contact['phone_mob'];
            $contact['portrait'] ? $chat_list[$key]['portrait'] = $contact['portrait'] : $chat_list[$key]['portrait'] = Conf::get('default_user_portrait');
            empty($contact['portrait']) && $chat_list[$key]['contact_portrait'] = Conf::get('default_user_portrait');
            $chat_list[$key]['user_id'] = $this->_user_id;
//            $chat_list[$key]['phone_mob'] = $this->visitor->get('phone_mob');

        }
        $userInfo = $this->_member_mod->get(array(
            'fields' => 'user_name,portrait,user_id',
            'conditions' => 'user_id=' . $_GET['otherid'],
        ));

        $this->assign('chat_list', $chat_list);
        $this->assign('userInfo', $userInfo);
        $this->assign('other_id', $_GET['otherid']);
        $this->display('my_chatlog.view.html');
    }

    function _get_member_submenu()
    {
        $menus = array(
            array(
                'name' => 'my_chat_list',
                'url' => 'index.php?app=my_chatlog',
            )

        );
        ACT == 'reply' && $menus[] = array(
            'name' => 'reply',
        );
        return $menus;
    }

    function send()
    {
        if (!$_GET['reveiver_id']) {
            $this->show_warning($this->_chatlog_mod->get_error());
        }
        if (!$_POST['description']) {
            $this->show_warning('请填写回复内容！~');
            return;
        }
        $data = array(
            'senderid' => $this->_user_id,
            'receiverid' => $_GET['reveiver_id'],
            'sendcontent' => $_POST['description'],
            'sendtime' => time(),
        );
        $res = $this->_chatlog_mod->add($data);


        if (!$res) {
            $this->show_warning('添加失败');
        }

        $sql = 'UPDATE ecm_chatlog SET is_read = 2 where (senderid = ' . $this->_user_id . ' OR receiverid = ' . $this->_user_id . ') AND ' . '(senderid = ' . $_GET['reveiver_id'] . ' OR receiverid = ' . $_GET['reveiver_id'] . ')';
        $res = $this->_chatlog_mod->db->query($sql);
        $this->show_message('添加成功');
    }

}
